# coding: utf-8
from pathlib import Path
from typing import Union

from pandas import DataFrame
from yaml import safe_load, safe_dump

from .engin_base import FileEngineBase, ApiJsonTemplate, UiJsonTemplate


class YamlEngine(FileEngineBase):
    def _openDataFrame(self, sheet_name: str = None) -> DataFrame:
        with open(self.fileName, 'r', encoding=self.encoding) as fp:
            return DataFrame(safe_load(fp.read()))

    @classmethod
    def write(cls, data: Union[list, dict], fileName: Union[str, Path] = None):
        if isinstance(data, dict):
            data = [data]
        if fileName is None:
            fileName = cls.fileName
        with open(fileName, 'w', encoding=cls.encoding) as fp:
            safe_dump(data, fp, allow_unicode=True, encoding=cls.encoding, indent=4, sort_keys=False,
                      default_style=False)

    @classmethod
    def ApiTemplate(cls, fileName: Union[str, Path]):
        cls.write(cls.to_dict(ApiJsonTemplate), fileName=fileName)

    @classmethod
    def UiTemplate(cls, fileName: Union[str, Path]):
        cls.write(UiJsonTemplate, fileName=fileName)
